package com.learn.swagger.result;


import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * 返回结果的实体
 *
 * @author zhousiqi
 * @version 1.0.0
 * @date 2019/2/26 13:22
 */
@Getter
@ApiModel("结果包装")
public class Result<T> implements Serializable {
    private static final long serialVersionUID = -619545792932454244L;
    private static final int SUCCESS_CODE = 0;

    /**
     * 返回码
     */
    @ApiModelProperty(value = "返回码", required = true)
    private int code;

    /**
     * 返回信息
     */
    @ApiModelProperty(value = "返回消息", required = true)
    private String message;

    /**
     * 时间戳
     */
    @ApiModelProperty(value = "时间戳", required = true)
    private Long timestamp;

    /**
     * 返回内容
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @ApiModelProperty(value = "返回的数据")
    private T data;

    public Result(int code, String message) {
        this.code = code;
        this.message = message;
        setTimestamp();
    }

    public Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
        setTimestamp();
    }

    public static <T> Result<T> ofSuccess(String msg) {
        return new Result<>(SUCCESS_CODE, msg);
    }

    public static <T> Result<T> ofSuccess(String msg, T body) {
        return new Result<>(SUCCESS_CODE, msg, body);
    }

    public static <T> Result<T> ofFailure(int code, String msg) {
        return new Result<>(code, msg);
    }

    public static <T> Result<T> ofFailure(int code, String msg, T body) {
        return new Result<>(code, msg, body);
    }


    /**
     * 默认设置时间戳为当前时间
     */
    private void setTimestamp() {
        this.timestamp = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }
}
